<template>
	<view class="container">
        <u-form :model="form" ref="form" label-width="140">
		    <u-form-item label="收货人" prop="receiver"><u-input v-model="form.receiver" placeholder="请填写收货人"/></u-form-item>
		    <u-form-item label="手机号码" prop="mobile"><u-input v-model="form.mobile" placeholder="请填写手机号码"/></u-form-item>
		    <u-form-item label="选择地区">
                <u-input v-model="form.address" type="select" placeholder="请选择地区" :select-open="show" @click="show=true"/>
            </u-form-item>
		    <u-form-item label="详细地址" prop="detail"><u-input v-model="form.detail" type="textarea" placeholder="请填写详细地址"/></u-form-item>
		    <u-form-item v-if="id" label="是否默认"><u-switch slot="right" v-model="form.isDefault" active-color="#59C4CA"></u-switch></u-form-item>
	    </u-form>

        <!-- 地区选择 -->
        <u-select slot="right" v-model="show" mode="mutil-column-auto" :list="list" @confirm="selectAddress" :default-value="addressArr"></u-select>

        <!-- 编辑/添加 -->
		<button class="btn-confirm" @click="submit" :loading="isLoading">{{id ? '确认编辑' : '添加地址'}}</button>

        <u-toast ref="uToast" />
	</view>
</template>
<script>
import Vue from 'vue';
import { addAddressAPI, updateAddressAPI } from '../../api/address'
import { DefaultAddress } from '../../api/config/enums'

const app = getApp()
export default Vue.extend({
    data(){
        return {
            id: '',
            form: {
                receiver: '',
                mobile: '',
                detail: '',
                province: '', // 省
                city: '', // 市
                district: '', // 区县
                address: '',
                isDefault: false,
            },
            addressArr: [0, 0, 0],
            show: false,
            isLoading: false,
			list: [], // 处理后的省市县列表
            addressList: app.globalData.addressList,
            rules: {
				receiver: [
					{ 
						required: true, 
						message: '请输入收货人姓名', 
					}
				],
				mobile: [
					{ 
						required: true, 
						message: '请输入手机号码', 
					},
                    {
			            validator: (rule, value, callback) => value.length === 11,
			            message: '请输入正确手机号码'
		            },
				],
				detail: [
					{ 
						required: true, 
						message: '请输入详细地址', 
					}
				],
			}
        }
    },
    onLoad(options){
        let { id } = options

        // 处理地区选择器数据
        this.list = this.handleCities(app.globalData.addressList)
        
        // 编辑地址时，需要初始化省市县名称和省市县列表
        if(id){
            this.id = id
            this.form = {
                receiver: options.receiver,
                mobile: options.mobile,
                detail: options.detail,
                province: options.province, // 省
                city: options.city, // 市
                district: options.district, // 区县
                address: options.address,
                isDefault: options.isDefault == 1,
            }
            this.form.address = this.getAddress(options)
            this.getAddressArr(options)
        }
    },
    onReady() {
		this.$refs.form.setRules(this.rules);
	},
    methods: {
        // 获取省市县名称
        getAddress(item){
            try{
                let pId = item.province
                let cId = item.city
                let dId = item.district
                let province, city, district

                province = this.addressList.find(p => p.id == pId)
                if(province) city = province.listCity.find(c => c.id == cId)
                if(city) district = city.listDistrict.find(d => d.id == dId)
                let provinceName = province ? province.name : ''
                let cityName = city ? city.name : ''
                let districtName = district ? district.name : ''
                return `${provinceName} ${cityName} ${districtName}`
            }catch(err){
                this.$refs.uToast.show({
				    title: '初始化地址名称错误',
				    type: 'error',
                }) 
            }
        },
        // 编辑地址时，初始化省市县列表
        getAddressArr(item){
            try{
                let pId = item.province
                let cId = item.city
                let dId = item.district
                let province, city, district

                this.addressList.forEach((p, index) => {
                    if(p.id == pId){
                        province = p
                        this.addressArr[0] = index
                    }
                })
                if(province) {
                    province.listCity.find((c, index) => {
                        if(c.id == cId){
                            city = c
                            this.addressArr[1] = index
                        }
                    })
                }
                if(city) {
                    city.listDistrict.find((d, index) => {
                        if(d.id == dId){
                            this.addressArr[2] = index
                        }
                    })
                }
            }catch(err){
                this.$refs.uToast.show({
				    title: '初始化地址选择器错误',
				    type: 'error',
                })
            }
        },
        selectAddress(selectedArr){
            let p = selectedArr[0]
            let c = selectedArr[1]
            let d = selectedArr[2]
            this.form.address = `${p.label || ''} ${c.label || ''} ${d.label || ''}`
            this.form.province = p.value
            this.form.city = c.value
            this.form.district = d.value
        },
        submit(){
            this.$refs.form.validate(valid => {
				if (valid) {
                    this.isLoading = true
                    let promise
                    let params = {
                            sessionId: app.globalData.sessionId,
                            receiver: this.form.receiver,
	                        mobile: this.form.mobile,
	                        province: this.form.province,
	                        city: this.form.city,
	                        district: this.form.district,
	                        detail: this.form.detail,
	                        isDefault: this.form.isDefault ? DefaultAddress.Yes : DefaultAddress.No
                        }
                    if(this.id){
                        params.id = this.id
                        promise = updateAddressAPI(params)
                    } else {
                        promise = addAddressAPI(params)
                    }
                    promise.then(res => {
                        this.isLoading = false
                        this.$refs.uToast.show({
				    	    title: this.id ? '编辑成功' : '添加成功',
				    	    type: 'success',
                            callback: () => {
                                this.$u.route({type: 'navigateBack'})
                            }
                    	})
                    }).catch(err => {
                        this.$refs.uToast.show({
				    	    title: err,
				    	    type: 'error',
                    	})
                    })
				}
			});
        },
        handleCities(list){
            return list.map(item => {
                let s = {
                    label: item.name,
                    value: item.id
                }
                if(item.listCity) {
                    s.children = this.handleCities(item.listCity)
                }
                if(item.listDistrict) {
                    s.children = this.handleCities(item.listDistrict)
                }
                return s
            })
        }
    }
})
</script>
<style lang="scss" scoped>
@import '../../assets/scss/common.scss';

.container{
    padding: 0 10px;
}
.btn-confirm{
	background-color: $theme-color;
	color: #fff;
	position: absolute;
	bottom: 100rpx;
	left: 10vw;
	width: 80vw;
	margin: 0 auto;
}
</style>